package v1

import (
	"github.com/gin-gonic/gin"
	"ota/bll"
	"ota/model"
	"ota/server/web/middleware"
	"ota/utils"
)

var Ota = &ota{}

func init() {
	// 注册路由
	RegisterRouter(Ota)
}

type ota struct{}

// Init 初始化路由
func (a *ota) Init(r *gin.RouterGroup) {
	// app 路由
	appG := r.Group("app", middleware.Auth())
	{
		appG.POST("/checkVersion", a.checkVersion) // 检测版本升级计划
		appG.POST("/upgrade", a.upgrade)           // 确认是否升级（自主/强制)
		appG.POST("/record", a.record)             // 获取升级记录
		appG.POST("/result", a.result)             // 获取升级结果
	}
}

func (a *ota) checkVersion(c *gin.Context) {
	var (
		err error
		in  = &model.OtaCheckVersionRequest{}
		out = &model.OtaCheckVersionResponse{}
	)

	if err = c.ShouldBindJSON(in); err != nil {
		_ = c.Error(err)
		return
	}

	if out, err = bll.Ota.CheckVersion(c.Request.Context(), in); err != nil {
		_ = c.Error(err)
		return
	}
	utils.ResponseOk(c, out)
}

func (a *ota) upgrade(c *gin.Context) {
	var (
		err error
		in  = &model.OtaUpgradeRequest{}
	)
	if err = c.ShouldBindJSON(in); err != nil {
		_ = c.Error(err)
		return
	}

	if err = bll.Ota.Upgrade(c.Request.Context(), in); err != nil {
		_ = c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

func (a *ota) record(c *gin.Context) {
	var (
		err error
		in  = &model.OtaRecordRequest{}
		out = &model.OtaRecordResponse{}
	)
	if err = c.ShouldBindJSON(in); err != nil {
		_ = c.Error(err)
		return
	}
	if out, err = bll.Ota.Record(c.Request.Context(), in); err != nil {
		_ = c.Error(err)
		return
	}

	utils.ResponseOk(c, out)
}

func (a *ota) result(c *gin.Context) {
	var (
		err error
		in  = &model.OtaResultRequest{}
		out = &model.OtaResultResponse{}
	)
	if err = c.ShouldBindJSON(in); err != nil {
		_ = c.Error(err)
		return
	}
	if out, err = bll.Ota.Result(c.Request.Context(), in); err != nil {
		_ = c.Error(err)
		return
	}
	utils.ResponseOk(c, out)
}
